﻿/**@brief
 * ring buffer
 *@  date:2013-12-18
* ringbuffer.h
 * */

#ifndef RINGBUFFER_HEADER_H 
#define RINGBUFFER_HEADER_H

#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>


//判断x是否是2的次方
#define is_power_of_2(x) ((x) != 0 && (((x) & ((x) - 1)) == 0))
//取a和b中最小值
#define min(a, b) (((a) < (b)) ? (a) : (b))

#ifdef _IN_LINUX_
struct ring_buffer
{
	uint8_t         *buffer;     //缓冲区
    uint32_t     size;       //大小
    uint32_t     in;         //入口位置
    uint32_t       out;        //出口位置
	pthread_mutex_t *f_lock;    //互斥锁
};
#else
typedef struct ring_buffer
{
    uint8_t         *buffer;     //缓冲区
    uint32_t     size;       //大小
    volatile uint32_t     in;         //入口位置
    volatile uint32_t     out;        //出口位置
}ring_buffer;
#endif


//求比val大的最近的一个2次幂数
unsigned long roundup_power_of_two(unsigned long val);

//初始化缓冲区
struct ring_buffer* __ring_buffer_init( struct ring_buffer *ring_buf, uint8_t *buffer, uint32_t size);

//重置
void __ring_buffer_reset(struct ring_buffer *ring_buf);

//缓冲区的长度
uint32_t __ring_buffer_len(const struct ring_buffer *ring_buf);

//从缓冲区中取数据
uint32_t __ring_buffer_get(struct ring_buffer *ring_buf, uint8_t * buffer, uint32_t size);

//向缓冲区中存放数据
uint32_t __ring_buffer_put(struct ring_buffer *ring_buf, uint8_t * buffer, uint32_t size);

//从buffer里面读取大小size的数据块,避免内存copy
void * __ring_buffer_readdata(struct ring_buffer *ring_buf,  uint32_t size);

//从buffer里面获取大小size的空闲buffer
void * __ring_buffer_getfreeroom(struct ring_buffer *ring_buf,  uint32_t size);


#ifdef _IN_LINUX_

struct ring_buffer* ring_buffer_init( struct ring_buffer *ring_buf, void *buffer, uint32_t size, pthread_mutex_t *f_lock);

uint32_t ring_buffer_len(const struct ring_buffer *ring_buf);

uint32_t ring_buffer_get(struct ring_buffer *ring_buf, void *buffer, uint32_t size);

uint32_t ring_buffer_put(struct ring_buffer *ring_buf, void *buffer, uint32_t size);
#endif

#endif //RINGBUFFER_HEADER_H
